package com.jingbaoduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jingbaoduo.common.BaseContext;
import com.jingbaoduo.common.R;
import com.jingbaoduo.domain.Address;
import com.jingbaoduo.service.AddressService;
import com.jingbaoduo.vo.AddressVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("/{userId}")
    public R<List<Address>> list(@PathVariable Long userId){
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId,userId);
        queryWrapper.orderByDesc(Address::getIsDefault).orderByDesc(Address::getUpdateTime);

        List<Address> list = addressService.list(queryWrapper);

        if(list.isEmpty()){
            return R.error("您还没有收获地址");
        }
        return R.success(list);

    }

    @PostMapping
    public R<String> saveOrUpdate(@RequestBody Address address){

        //设置用户id
        Long currentId = BaseContext.getCurrentId();
        address.setUserId(currentId);

        //如果传入的为默认地址则将其他地址修改为普通
        if (address.getIsDefault() == 1){
            //查询目前的默认地址
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Address::getIsDefault,0);

            Address one = addressService.getOne(queryWrapper);

            //修改为O
            addressService.updateDefault(one);
        }

        //传入的address没有id则为添加操作
        if (address.getId() == null || "".equals(address.getId())){
            //设置创建更改时间
            address.setCreateTime(LocalDateTime.now());
            address.setUpdateTime(LocalDateTime.now());
            addressService.save(address);
        }
        //传入的address有id则为更新操作
        else {
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<Address>();
            queryWrapper.eq(Address::getId,address.getId());

            //设置修改时间
            address.setUpdateTime(LocalDateTime.now());
            addressService.update(address,queryWrapper);
        }

        return R.success("地址保存成功");

    }
}
